import "./index.less"
import { Space, Table, Tag, Input, Button, message, TablePaginationConfig, Modal, Form, Switch, DatePicker } from 'antd';
const { RangePicker } = DatePicker;
import dayjs from 'dayjs';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { fileUpload,addActive,updateActive } from "@/api/active";
import systme from "@/api/constant"
import { useNavigate,useLocation } from "react-router-dom";



interface ActiveDataType {
    content: string,
    pubDate: string,
    endDate: string,
    userId: string,
    title: string,
    dateArr: any
}
let userId = JSON.parse(sessionStorage.getItem("user") as string).id





export default function editActive() {
    const router = useNavigate()
    let {state} = useLocation()
    const [ActiveData, setActiveData] = useState<ActiveDataType>(
        {
            content: '',
            pubDate: '',
            endDate: '',
            userId: '',
            title: '',
            dateArr: []
        }
    )

    const handlerTime = (e: any) => {
        
        setActiveData({ ...ActiveData, pubDate: e[0].$d, endDate: e[1].$d,dateArr:e })
    }
    const handerChange = (e: any) => {
        setActiveData({ ...ActiveData, title: e.target.value })
    }

    const [editor, setEditor] = useState<IDomEditor | null>(null)
    
    const [html, setHtml] = useState('')

    useEffect(() => {
        console.log(state);
        
        if(state){
            setActiveData({...state,dateArr:[dayjs(state.pubDate),dayjs(state.endDate),userId]})
            setHtml(state.content)
            setBtnText("修改")
        }else{
            setBtnText("创建")
            setActiveData({ ...ActiveData,userId})
        }
    }, [])

    const toolbarConfig: Partial<IToolbarConfig> = {}
    const editorConfig: Partial<IEditorConfig> = {    
        placeholder: '请输入内容...',
        MENU_CONF:{
            uploadImage:{
                 customUpload: async(file: any, insertFn: any)=> {
                    // file 需要自己调用上传后端接口
                     let formData:FormData = new FormData()
                     formData.append("uploadFile",file)
                    const res = await fileUpload(formData)
                    if(res.code == 200){
                        insertFn(res.data,"图片无法加载。。。",res.data)
                        setHtml((editor as IDomEditor).getHtml())
                    }else{
                        message.error(res.msg||"上传失败")
                    }
                    // 然后使用 insertFn(url, alt, href) 回调编辑器显示
                    // insertFn();
                }
            }
        }
    }
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    const handlerAdd = () =>{
        let params = { ...ActiveData,content:(editor as IDomEditor).getHtml()}
        if(!ActiveData.title){
            message.error("未输入活动名称")
            return
        }
        if(!ActiveData.pubDate || !ActiveData.endDate){
            message.error("未输入活动时间")
            return
        }
        if(btnText == '创建'){
            handlerAddEdit(params)
        }else if(btnText == '修改'){
            handerUpdateEdit(params)
        }
    }


    const handlerAddEdit = (params:any)=>{
        addActive(params).then((res)=>{
            if(res.code == 200){
               message.success("创建活动成功")
               router("/home/active")
            }else{
               message.error(res.msg||systme.ERROR_MESSAGE)
            }
       }).catch((err)=>{
           message.error(systme.ERROR_MESSAGE)
       })
    }
    
    const handerUpdateEdit = (params:any) =>{
        updateActive(params).then((res)=>{
            if(res.code == 200){
               message.success("修改活动成功")
               router("/home/active")
            }else{
               message.error(res.msg||systme.ERROR_MESSAGE)
            }
       }).catch((err)=>{
           message.error(systme.ERROR_MESSAGE)
       })
    }  



    const [btnText,setBtnText] = useState<string>()
    return (
        <div className="box_views">
            <div className="header">
               {btnText}活动
            </div>
            <div className="form flex_a">
                <span className="title">活动名称：</span>
                <div className="input"><Input placeholder="请输入" value={ActiveData.title} onChange={(e) => { handerChange(e) }} /></div>
            </div>
            <div className="form flex_a">
                <span className="title">活动时间：</span>
                <RangePicker onChange={(e) => { handlerTime(e) }} value={ActiveData.dateArr} />
            </div>
            <div className="form flex">
                <span className="title">活动内容：</span>
                <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                    <Toolbar
                        editor={editor}
                        defaultConfig={toolbarConfig}
                        mode="default"
                        style={{ borderBottom: '1px solid #ccc' }}
                    />
                    <Editor
                        defaultConfig={editorConfig}
                        value={html}
                        onCreated={setEditor}
                        onChange={editor => {
                            setHtml(editor.getHtml())
                        }}
                        mode="default"
                        className="wangEditor__editor"
                        style={{ height: '500px', overflowY: 'hidden' }}
                    />
                </div>
            </div>
            <div className="form flex">
            <span>&emsp;&emsp;&nbsp;操作：</span>
            <Button type="primary" size="middle" onClick={handlerAdd}>{btnText}</Button>
            </div>
        </div>
    )
}